package com.fastdfs.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fastdfs.pojo.AlbumImageitems;
import com.fastdfs.pojo.Imageitems;
import com.fastdfs.service.AlbumImageitemsService;
import com.fastdfs.service.ImageitemsService;
import com.fastdfs.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@RestController
@RequestMapping("/albumImageitems")
public class AlbumImageitemsControler {



    @Autowired
    private AlbumImageitemsService albumImageitemsService;
    @Autowired
    private  ImageitemsService imageitemsService;


    /**
     * 查询 指定相册内全部图片  (分页)
     * @param id
     * @param  page 页
     * @param  size  每页显示数量
     * @return
     * @throws Exception
     */

    @GetMapping("/{id}/{page}/{size}")
    public Result<Imageitems> selectAll(@PathVariable String id, @PathVariable  int page, @PathVariable  int size) throws Exception {
        // 先 获取缓存 数据 如果没有的话在 从数据库里获取

        String stringRedis = RedisUtis.getStringRedis(id);

        if(NullUtils.notEmpty(stringRedis )){
                List<Imageitems> list =JsonTurnUtils.jsonTurnList(stringRedis ,Imageitems.class);
                System.out.println(list);
                Page<Imageitems> page1 = new Page<>(page, size, list);
                System.out.println("查询 指定相册内全部图片  (分页)---缓存读取");
                System.out.println(page1);
                return new Result<Imageitems>(true, StatusCode.OK,"查询成功",page1);
        }

        AlbumImageitems albumImageitems=new AlbumImageitems();
        albumImageitems.setAlbumId(id);
        List<Imageitems> list = albumImageitemsService.selectALL(albumImageitems); //总数据
        RedisUtis.setStringRedis(id,list);  //设置缓存
        Page<Imageitems> page1 = new Page<>(page, size,list);  //分页后数据
        System.out.println("查询 指定相册内全部图片  (分页)--- 数据库读取");
        return new Result<Imageitems>(true, StatusCode.OK,"查询成功",page1);
    }



    //删除相册 内 第几页 的 某张图片

    /**
     * @param albumId  相册 id
     * @param imageId  图片id
     * @return
     * @throws Exception
     */

    @GetMapping("/deleteOne")
    public Result deleteOne(String albumId, String imageId) throws Exception {

        //删除缓存
        System.out.println("deleteOne");
        Imageitems imageitems=null;


        String stringRedis = RedisUtis.getStringRedis(albumId);
        List<Imageitems> objects = JsonTurnUtils.jsonTurnList(stringRedis,Imageitems.class);
        for (Imageitems imageitems1 : objects) {
            if(imageitems1.getId().equals(imageId)){
                objects.remove(imageitems1);
                System.out.println("缓存删除成功");
                imageitems=imageitems1;
                break;
            }
        }

        RedisUtis.setStringRedis(albumId,objects);
        System.out.println("重新载入缓存成功" );

        System.out.println(imageitems);
        // 物理删除
        Map<String,Object>  mp=new HashMap();
        mp.put("group",imageitems.getImageGroup());
        mp.put("fileName",imageitems.getImagePath());
        // 删除相册封面 的物理图片
        String s = HttpUtils.doDelete("http://localhost:20210/album/deleteFile", mp);
        Map<String, Object> turn = JsonTurnUtils.jsonTurnMap(s);
        if( !(Boolean) turn.get("flag") ){
            return new Result(false, StatusCode.OK,"物理图片删除失败");
        }
        System.out.println("物理删除成功");

        try {
            imageitemsService.delete(imageId);
            AlbumImageitems albumImageitems=new AlbumImageitems();
            albumImageitems.setImageitemsId(imageId);
            albumImageitemsService.deleteOne(albumImageitems);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.OK,"删除数据库图片失败");
        }


        System.out.println("数据库删除成功");
        return new Result(true, StatusCode.OK,"删除成功");

    }




    //添加图片
    @PostMapping("/ins/{id}")
    public Result add(@RequestParam("file") MultipartFile[] multipartFiles,@PathVariable String id,Model model) throws Exception {
        Map<String, Object> stringObjectMap = model.asMap(); //获取全局配置的 变量
        Map<String,String> ma= (Map<String, String>) stringObjectMap.get("md");
        String http =(String) ma.get("http");
        System.out.println(id);
        if (multipartFiles==null||multipartFiles.length==0){
            return new Result(false, StatusCode.OK,"上传图片异常 ",null);
        }
        String s = HttpUtils.httpClientUploadFile( http +"/album/uploads/", multipartFiles);
        System.out.println("添加物理图片成功");
        JSONObject jsonObject = JSON.parseObject(s);
        JSONArray data1 = jsonObject.getJSONArray("data");
        System.out.println(data1);
        List<Result> results = data1.toJavaList(Result.class);
        System.out.println(results.get(0).getData());
        for (Result  result : results) {
            if(!result.isFlag()){//判断是否上传成功
               return new Result(false, StatusCode.OK,"添加失败",null);
            }
            AlbumImageitems  albumImageitems=new AlbumImageitems();
            albumImageitems.setId(Id_Builder.nextId());
            albumImageitems.setAlbumId(id);
            String objbean=JSON.toJSONString( result.getData());
            Imageitems dept= JSONObject.parseObject(objbean, Imageitems.class);
            albumImageitems.setImageitemsId(dept.getId());
            albumImageitemsService.add(albumImageitems);

            //添加缓存
            String stringRedis = RedisUtis.getStringRedis(id);
            List<Imageitems> objects = JsonTurnUtils.jsonTurnList(stringRedis,Imageitems.class);
            objects.add(dept);
            RedisUtis.setStringRedis(id,objects);


        }
        System.out.println("添加缓存成功");
        return new Result(true, StatusCode.OK,"添加成功",s);
    }




}
